$(function () {
    $("#showInsertUserDialog").click(showInsertUserDialog);
    $("#insertUser").click(insertUser);
    $("#updateUser").click(updateUser);
    $("#queryUserButton").click(queryUser);
    $("#resetUserButton").click(resetUserButton);
    fillPageDataListTable();
    /*    fillQueryPageDataListClasszSelect();
        initOrganizationInfo();
        initQueryUserSelectChange();*/

    layui.use(['laydate'], function () {
        var laydate = layui.laydate;
        //日期时间选择器
        laydate.render({
            elem: '#userRegistertimeFrom',
            type: 'date'
        });

        laydate.render({
            elem: '#userRegistertimeTo',
            type: 'date'
        });


    });
})

function initQueryUserSelectChange() {
    layui.use(['form'], function () {
        var form = layui.form;
        form.on('select(queryClasszSelect)', function (data) {
            fillPageDataListTable();
        });
        form.on('select(sex)', function (data) {
            fillPageDataListTable();
        });
    });
}

function fillQueryPageDataListClasszSelect() {
    $.post("/classzapplicationform/queryClasszListByOrganizationId?t=" + new Date().getTime(), function (data) {
        var jsonObject = JSON.parse(data);
        if (jsonObject.responseCode == 500) {
            layer.msg(jsonObject.message);
        }
        if (jsonObject.responseCode == 501) {
            layer.msg("系统级异常：" + jsonObject.message);
        }
        if (jsonObject.responseCode == 200) {
            var getClasszList = jsonObject.responseData;
            for (var i = 0; i < getClasszList.length; i++) {
                var eachClassz = getClasszList[i];
                var classzId = eachClassz.id;
                var classzName = eachClassz.classzName;

                var newOption = $("<option></option>");
                $(newOption).text(classzName);
                $(newOption).val(classzId);

                $("#queryUserTable select[name='queryClasszSelect']").append(newOption);
            }

            layui.use('form', function () {
                var form = layui.form;
                form.render();
            });
        }
    });
}

function queryUser() {
    $("#queryUserTable input[type='hidden'][name='gotoPageHidden']").val("1")
    fillPageDataListTable();
}

function resetUserButton() {
    $("#queryUserTable :text[name='userIphone']").val("");
    $("#queryUserTable :text[name='userNickname']").val("");
    $("#queryUserTable :text[name='userRegistertimeFrom']").val("");
    $("#queryUserTable :text[name='userRegistertimeTo']").val("");
    $("#queryUserTable :text[name='userStatus']").val("-1");

    layui.use('form', function () {
        var form = layui.form;
        form.render();
    });

    queryUser();
}

function fillPageDataListTable() {
    var userIphone = $("#queryUserTable :text[name='userIphone']").val();
    var userNickname = $("#queryUserTable :text[name='userNickname']").val();
    var userRegistertimeFrom = $("#queryUserTable :text[name='userRegistertimeFrom']").val();
    var userRegistertimeTo = $("#queryUserTable :text[name='userRegistertimeTo']").val();
    var userStatus = $("#queryUserTable select[name='userStatus'] option:selected").val();
    var gotoPage = $("#queryUserTable input[type='hidden'][name='gotoPageHidden']").val();
    console.log("post")

    $.post("/api/users/getAll", {
        "userIphone": userIphone,
        "userNickname": userNickname,
        "userRegistertimeFrom": userRegistertimeFrom,
        "userRegistertimeTo": userRegistertimeTo,
        "userStatus": userStatus,
        "gotoPage": gotoPage
    }, function (data) {
        var jsonstr= JSON.stringify(data);
        var jsonObject = JSON.parse(jsonstr);
        if (jsonObject.responseCode == 500) {
            layer.msg(jsonObject.message);
        }
        if (jsonObject.responseCode == 501) {
            layer.msg("系统级异常：" + jsonObject.message);
        }
        if (jsonObject.responseCode == 200) {
            {
                var pageDataListTable = $("#pageDataListTable");
                $(pageDataListTable).find("tbody").empty();

                var queryPageDataList = jsonObject.data.pageData;
                console.log(queryPageDataList);
                if (queryPageDataList.length == 0 && gotoPage > 1) { //实现当前页删光显示前一页
                    $("#queryUserTable input[type='hidden'][name='gotoPageHidden']").val(gotoPage - 1);
                    fillPageDataListTable();
                }
                if (queryPageDataList.length == 0) {
                    $(pageDataListTable).append(createTableEmpty());
                } else {
                    for (var i = 0; i < queryPageDataList.length; i++) {
                        var newTR = createEachUserTR(queryPageDataList[i]);
                        $(pageDataListTable).find("tbody").append(newTR);
                    }
                }
            }

            {
                var gotoPage = jsonObject.data.gotoPage;
                var getAllPageRecordCount = jsonObject.data.getAllPageRecordCount;
                var getCurrentPageRecordCount = jsonObject.data.getCurrentPageRecordCount;
                var pageSize = jsonObject.data.pageSize;
                layui.use(['laypage'], function () {
                    var laypage = layui.laypage;
                    //分页导航自定义样式
                    laypage.render({
                        elem: 'pageComponent',
                        count: getAllPageRecordCount,
                        limit: pageSize,
                        groups: 20,
                        theme: '#1E9FFF',
                        curr: gotoPage,
                        jump: function (obj, first) {
                            if (!first) {
                                var clickGotoPage = obj.curr;//获取当前点击页码
                                $("#queryUserTable input[type='hidden'][name='gotoPageHidden']").val(clickGotoPage);
                                fillPageDataListTable();
                            }
                        }
                    });
                });

                $("#gotoPageTable button[name='getAllPageRecordCount']").text("所有页的总记录数：" + getAllPageRecordCount);
                $("#gotoPageTable button[name='getCurrentPageRecordCount']").text("当前页的记录数：" + getCurrentPageRecordCount);
            }
        }
    });
    console.log("ajax")
    /*$.ajax({
        url: "/api/users/getAll",
        method: 'POST',
        data: {
            "userIphone": userIphone,
            "userNickname": userNickname,
            "userRegistertimeFrom": userRegistertimeFrom,
            "userRegistertimeTo": userRegistertimeTo,
            "userStatus": userStatus,
            "gotoPage": gotoPage
        },
        success: function (data) {
           var jsonstr= JSON.stringify(data);
            var jsonObject = JSON.parse(jsonstr);
            if (jsonObject.responseCode == 500) {
                layer.msg(jsonObject.message);
            }
            if (jsonObject.responseCode == 501) {
                layer.msg("系统级异常：" + jsonObject.message);
            }
            if (jsonObject.responseCode == 200) {
                {
                    var pageDataListTable = $("#pageDataListTable");
                    $(pageDataListTable).find("tbody").empty();

                    var queryPageDataList =  jsonObject.data;
                    console.log(queryPageDataList)
                    if (queryPageDataList.length == 0 && gotoPage > 1) {//实现当前页删光显示前一页
                        $("#queryUserTable input[type='hidden'][name='gotoPageHidden']").val(gotoPage - 1);
                        fillPageDataListTable();
                    }
                    if (queryPageDataList.length == 0) {
                        $(pageDataListTable).append(createTableEmpty());
                    } else {
                        for (var i = 0; i < queryPageDataList.length; i++) {
                            var newTR = createEachUserTR(queryPageDataList[i]);
                            $(pageDataListTable).find("tbody").append(newTR);
                        }
                    }
                }
    
                {
                    var gotoPage = jsonObject.data.gotoPage;
                    var getAllPageRecordCount = queryGotoMap.getAllPageRecordCount;
                    var getCurrentPageRecordCount = queryGotoMap.getCurrentPageRecordCount;
                    var pageSize = queryGotoMap.pageSize;
                    layui.use(['laypage'], function () {
                        var laypage = layui.laypage;
                        //分页导航自定义样式
                        laypage.render({
                            elem: 'pageComponent',
                            count: getAllPageRecordCount,
                            limit: pageSize,
                            groups: 20,
                            theme: '#1E9FFF',
                            curr: gotoPage,
                            jump: function (obj, first) {
                                if (!first) {
                                    var clickGotoPage = obj.curr;//获取当前点击页码
                                    $("#queryUserTable input[type='hidden'][name='gotoPageHidden']").val(clickGotoPage);
                                    fillPageDataListTable();
                                }
                            }
                        });
                    });
    
                    $("#gotoPageTable button[name='getAllPageRecordCount']").text("所有页的总记录数：" + getAllPageRecordCount);
                    $("#gotoPageTable button[name='getCurrentPageRecordCount']").text("当前页的记录数：" + getCurrentPageRecordCount);
                }
            }
        },
        error: function(data) {
            var jsonObject = JSON.parse(data);
            if (jsonObject.responseCode == 500) {
                layer.msg(jsonObject.message);
            }
            if (jsonObject.responseCode == 501) {
                layer.msg("系统级异常：" + jsonObject.message);
            }
        }
    })*/
}

function showEditUserDialog() {
    var userId = $(this).attr("userId");

    $.get("http://localhost:8091/api/users/"+userId, function (data) {
        var jsonstr = JSON.stringify(data);
        var jsonObject = JSON.parse(jsonstr);
        if (jsonObject.responseCode == 500) {
            layer.msg(jsonObject.message);
        }
        if (jsonObject.responseCode == 501) {
            layer.msg("系统级异常：" + jsonObject.message);
        }
        if (jsonObject.responseCode == 200) {
            var user = jsonObject.data;

            $("#editUserTable :text[name='userId']").val(user.userId);
            $("#editUserTable :text[name='userNum']").val(user.userNum);
            $("#editUserTable :text[name='userIphone']").val(user.userIphone);
            $("#editUserTable :text[name='userNickname']").val(user.userNickname);
            $("#editUserTable :text[name='userType']").val(user.userType);
            var dateObject = new Date(user.userRegistertime);
            var showDateString = dateObject.getFullYear() + "-" + dateObject.getMonth() + "-" + dateObject.getDate();
            $("#editUserTable :text[name='userRegistertime']").val(showDateString);
            $("#editUserTable :text[name='userStatus']").val(user.userStatus);

            layer.open({
                type: 1,
                title: '编辑用户',
                area: ['800px'],
                content: $("#editUserDivOut"),
                success: function (layero, index) {
                    //alert(layero + "  " + index);
                }
            });
        }
    });
}

function deleteUser() {
    var userId = $(this).attr("userId");
    layer.open(
        {
            type: 0,
            content: "确认删除用户？",
            btn: ['删除', '关闭'],
            yes: function (index, layero) {
                $.ajax({
                    method: "DELETE",
                    url: "/api/users/" + userId,
                    success: function (data) {
                        fillPageDataListTable();
                        layer.closeAll("dialog");
                    }

                });
            }
        }
    )
}

function createEachUserTR(eachUser) {
    var newTR = $("<tr></tr>");

/*
    var id_td = $("<td></td>");
    $(id_td).css("width", "150px");
    $(id_td).text(eachUser.userId);
*/

    var userId_td = $("<td></td>");
    $(userId_td).text(eachUser.userId);

    var userNum_td = $("<td></td>");
    $(userNum_td).text(eachUser.userNum);

    var userIphone_td = $("<td></td>");
    $(userIphone_td).text(eachUser.userIphone);

    var userNickname_td = $("<td></td>");
    $(userNickname_td).text(eachUser.userNickname);

    var userType_td = $("<td></td>");
    if (eachUser.userType==1){
        $(userType_td).text("学生");
    } else if (eachUser.userType==2) {
        $(userType_td).text("教师");
    }

    var userRegistertime_td = $("<td></td>");
    $(userRegistertime_td).text(eachUser.userRegistertime);

    var userStatus_td = $("<td></td>");
    if (eachUser.userStatus==0){
        $(userStatus_td).text("正常");

    } else {
        $(userStatus_td).text("禁用");
    }


    var operate_td = $("<td></td>");
    $(operate_td).css("width", "150px");
    var editUserA = $(`<button class="layui-btn layui-btn-sm layui-btn-normal"> <i class="layui-icon">&#xe642;</i></button>`);
    $(editUserA).attr("userId", eachUser.userId);
    $(editUserA).click(showEditUserDialog);
    var deleteUserA = $(`<button class="layui-btn layui-btn-sm layui-btn-danger"><i class="layui-icon">&#xe640;</i></button>`);
    $(deleteUserA).attr("userId", eachUser.userId);
    $(deleteUserA).click(deleteUser);
    $(operate_td).append(editUserA);
    $(operate_td).append(deleteUserA);

    $(newTR).append(userId_td);
    $(newTR).append(userNum_td);
    $(newTR).append(userIphone_td);
    $(newTR).append(userNickname_td);
    $(newTR).append(userType_td);
    $(newTR).append(userRegistertime_td);
    $(newTR).append(userStatus_td);
    $(newTR).append(operate_td);

    return newTR;
}

function insertUser() {
    var userId = $("#insertUserTable :text[name='userId']").val();
    var userName = $("#insertUserTable :text[name='userName']").val();
    var password = $("#insertUserTable :text[name='password']").val();
    var birthday = $("#insertUserTable :text[name='insertBirthday']").val();
    var sex = $("#insertUserTable select[name='userStatus'] option:selected").val();
    var phone = $("#insertUserTable :text[name='phone']").val();
    var email = $("#insertUserTable :text[name='email']").val();

    $.put("/api/users/", {
        "userId": userId,
        "userName": userName,
        "password": password,
        "birthday": birthday,
        "sex": sex,
        "phone": phone,
        "email": email,
    }, function (data) {
        var jsonObject = JSON.parse(JSON.stringify(data));
        if (jsonObject.responseCode == 500) {
            layer.msg(jsonObject.message);
        }
        if (jsonObject.responseCode == 501) {
            layer.msg("系统级异常：" + jsonObject.message);
        }
        if (jsonObject.responseCode == 200) {
            $("#insertUserTable :text[name='userId']").val("");
            $("#insertUserTable :text[name='userName']").val("");
            $("#insertUserTable :text[name='password']").val("");
            $("#insertUserTable :text[name='insertBirthday']").val("");
            $("#insertUserTable :text[name='sex']").val("1");
            $("#insertUserTable :text[name='phone']").val("");
            $("#insertUserTable :text[name='email']").val("");

            layui.use('form', function () {
                var form = layui.form;
                form.render();
            });

            fillPageDataListTable();
            layer.closeAll('page');
        }
    });
}

function updateUser() {
    var userId = $("#editUserTable :text[name='userId']").val();
    var userNum = $("#editUserTable :text[name='userNum']").val();
    var userIphone=$("#editUserTable :text[name='userIphone']").val();
    var userNickname=$("#editUserTable :text[name='userNickname']").val();
    var userType=$("#userType").val();
    var userRegistertime=$("#editUserTable :text[name='userRegistertime']").val();
    userRegistertime = userRegistertime.split("-");
    if (userRegistertime[1].length==1){userRegistertime[1]="0"+userRegistertime[1];}
    if (userRegistertime[2].length==1){userRegistertime[2]="0"+userRegistertime[2];}
    userRegistertime=userRegistertime.join("-");
    var userStatus=$("#editUserTable :text[name='userStatus']").val();

    $.ajax({method:"POST",url:"/api/users/update/", data:JSON.stringify({
        "userId": userId,
        "userNum": userNum,
        "userIphone": userIphone,
        "userNickname": userNickname,
        "userType": userType,
        "userRegistertime": userRegistertime,
        "userStatus": userStatus}), contentType:"application/json"}).
        done(function (data) {
            var jsonObject = JSON.parse(JSON.stringify(data));
            if (jsonObject.responseCode == 500) {
                layer.msg(jsonObject.message);
            }
            if (jsonObject.responseCode == 501) {
                layer.msg("系统级异常：" + jsonObject.message);
            }
            if (jsonObject.responseCode == 200) {
                fillPageDataListTable();
                layer.closeAll('page');
            }
        });
}

function showInsertUserDialog() {
    layer.open({
        type: 1,
        title: '添加用户',
        area: ['800px'],
        content: $("#insertUserDivOut"),
        success: function (layero, index) {
            $("#insertUserTable :text[name='userName']").val("");
            initOrganizationInfo();
        }
    });
}

function initOrganizationInfo() {
    $.post("/commons/getCookieLoginOrganizationInfo?t=" + new Date().getTime(), function (data) {
        var jsonObject = JSON.parse(data);
        if (jsonObject.responseCode == 500) {
            layer.msg(jsonObject.message);
        }
        if (jsonObject.responseCode == 501) {
            layer.msg("系统级异常：" + jsonObject.message);
        }
        if (jsonObject.responseCode == 200) {
            var cookieOrganizationInfo = jsonObject.responseData;

            var organizationId = cookieOrganizationInfo.organizationId;
            var organizationName = cookieOrganizationInfo.organizationName;

            $(":text[name='organizationName']").val(organizationName);
            $("input[type='hidden'][name='organizationId']").val(organizationId);
        }
    });
}

function createTableEmpty() {
    var newTR = $("<tr></tr>");
    var newTD = $("<td></td>");
    $(newTD).text("列表为空！");
    $(newTD).attr("colspan", 12);
    $(newTD).css("text-align", "center");
    $(newTR).append(newTD);
    return newTR;
}